<?php

class CompanyBranch extends Eloquent {
	 protected $table = 'company_branch';

	/**
	 * Condition: Unarchived Items.
	 * @author AngelaMisa 02/22/2015 2:25AM
	 * @param $query
	 * @return mixed
	 */
	public function scopeActive( $query ) {
		return $query->where($this->table . '.archived', 0);
	}
	
	/**
	 * Condition: Unarchived Orders.
	 * @author AngelaMisa 02/23/2015 9:51PM
	 * @return mixed
	 */
	public function scopeHasOrders( $query, $status = null ) {
		$query->whereHas('orders', function( $q ) use ( $status ) {
			$q->where('order.archived', 0);
			
			// @todo to optimize because too slow.
			if ( !is_null($status) ) {
				$q->whereHas('orderProducts', function ( $query ) use ( $status ) {
					$query->where('status', $status);
				});
			}
		});
	}

	/**
	 * Retrieves employees under branch.
	 * @author AngelaMisa 02/23/2015 9:51PM
	 * @return mixed
	 */
	public function employees() {
		return $this->hasMany('login', 'COMPANY_id');
	}
	
	/**
	 * Retrieves orders of employees under branch.
	 * @author AngelaMisa 02/23/2015 9:51PM
	 * @return mixed
	 */
	public function orders() {
		return $this->hasManyThrough('Order', 'Login', 'BRANCH_id', 'EMPLOYEE_id');
	}
}